<template>
	<div class="detail-main">
		<div class="export-box">
			<Button @click="exportQuickHandle(quick.id)" small="small" type="primary" class="quick"
				v-for="(quick, index) in exportQuick" :key="index">{{ quick.name }}</Button>
			<!-- 查询日期 -->
			<div class="query-time">
				<div class="time-start">
					<Date-picker type="datetime" format="yyyy-MM-dd HH:mm" placeholder="开始时间" clearable :editable="false"
						@on-change="timeStart"></Date-picker>
				</div>
				<div class="sitg">
					<span>至</span>
				</div>
				<div class="time-end">
					<Date-picker type="datetime" format="yyyy-MM-dd HH:mm" placeholder="结束时间" clearables :editable="false"
						@on-change="timeEnd"></Date-picker>
				</div>
			</div>
			<Button @click="queryDetail" small="small" type="primary">查询</Button>
			<Button @click="exportExcel" small="small" type="primary" class="export">导出excel</Button>
		</div>
		<Collapse v-model="open" style="padding:0">
			<Panel name="1">
				曲线
				<div slot="content">
					<chart :is="loaded" :chartData="result"></chart>
					<loading-bar :loading="loaded" height="400px"></loading-bar>
				</div>
			</Panel>
			<Panel name="2">
				概览
				<div slot="content">
					<summary-bar :is="summaryLoad" :summaryData="result"></summary-bar>
					<loading-bar :loading="summaryLoad" height="100px"></loading-bar>
				</div>
			</Panel>
			<Panel name="3">
				详细数据
				<div slot="content">
					<Table v-if="list" :columns="tablesName" :data="historyData" :highlight-row="true" size="small"></Table>
					<Page v-if="list" style="padding-top: 10px" :total="dataCount" :page-size="pageSize" size="small"
						show-elevator show-sizer @on-change="onChange" @on-page-size-change="changPage" show-total></Page>
					<loading-bar :loading="list" height="200px"></loading-bar>
				</div>
			</Panel>
		</Collapse>
	</div>
</template>

<script>
var loadingBar = {
	template: `
        <div v-if="!loading" :style="{height:height}" class="loading">
            <Col class="demo-spin-col" span="8">
            <Spin fix>
                <Icon type="load-c" size="18" class="load-bar"></Icon>
                <p class="load-text">加载中</p>
            </Spin>
            </Col>
        </div>
    `,
	props: ['loading', 'height']
}
import chart from '../components/chart'
import summaryBar from '../components/summary'
import moment from 'moment'
import xlsx from 'xlsx'
moment.locale('zh-cn')
const exportType = {
	bookType: 'xlsx',
	bookSST: true,
	type: 'binary'
} // 导出格式
export default {
	props: ['serialId', 'defaultTime'],
	components: {
		chart, // 曲线
		summaryBar, // 概述
		'loadingBar': loadingBar, // 加载
	},
	computed: {
		// 详情数据结果
		detailsData() {
			let data = this.result
			let arr = []
			if (data.length > 0) {
				let temp = data[0].startToReadTemp.split(',')
				let tempTime = moment(data[0].tempTime).format('X') // 记录时间unix
				temp.forEach((item, index) => {
					arr.push({
						'time': moment.unix(Number(tempTime) + index * Number(data[0].interval1) * 60).format('YYYY-MM-DD HH:mm:ss'),
						'data': item,
						'num': index + 1
					})
				})
				this.list = true
			}
			this.dataCount = arr.length
			return arr
		}
	},
	data() {
		return {
			result: [], // 详细数据
			loaded: null, // 是否请求到数据
			summaryLoad: null, // 概述是否有数据
			list: null, // 详细数据列表
			open: ['1', '2', '3'], // 折叠面板默认打开
			// 导出按钮快捷选项
			exportQuick: [
				{
					id: '1',
					name: '今天'
				}, {
					id: '2',
					name: '三天'
				}, {
					id: '3',
					name: '七天'
				}
			],
			tablesName: [
				{
					title: '序号',
					key: 'num'
				},
				{
					title: '记录时间',
					key: 'time'
				},
				{
					title: '温度',
					key: 'data'
				}
			],
			startTime: '', // 开始时间
			endTime: '', // 结束时间
			historyData: [], // 详情数据处理
			pageSize: 10, // 每页显示数量，
			dataCount: 0, // 初始化总共数量
			ajaxHistorData: [],
			exportType: exportType, // 导出excel配置
		}
	},
	methods: {
		// 选择开始时间
		timeStart(date) {
			this.startTime = date + ':00'
		},
		// 选择结束时间
		timeEnd(date) {
			this.endTime = date + ':00'
		},
		// 发送请求详细数据
		send_post_data(data) {
			this.$http.post('/query', data).then(res => {
				if (res.data.msg) {
					this.$Message.error(res.data.msg)
				} else {
					let result = res.data.data
					if (Object.keys(result).length > 0) {
						this.result = result
						// 因为请求数据慢，所以内容组件都懒加载
						this.$nextTick(() => {
							this.loaded = resolve => require(['@/components/chart'], resolve)
							this.summaryLoad = resolve => require(['@/components/summary'], resolve)
						})
					} else {
						this.$Message.warning('没有任何数据记录！')
					}
				}
			})
		},
		// 请求参数
		get_data() {
			let data = {
				query_type: 5,
				serialId: this.serialId,
				startTime: '2000-01-01 01:30:10',
				endTime: moment().format('YYYY-MM-DD HH:mm:ss')
			}
			this.send_post_data(data)
		},
		// 点击查询
		queryDetail() {
			let data = {
				query_type: 2,
				serialId: this.serialId,
				startTime: this.startTime ? this.startTime : '2000-01-01 01:30:10',
				endTime: this.endTime ? this.endTime : moment().format('YYYY-MM-DD HH:mm:ss')
			}
			this.send_post_data(data)
		},
		// 分页
		handleListApproveHistory() {
			this.ajaxHistorData = this.detailsData
			if (this.detailsData.length < this.pageSize) {
				this.historyData = this.ajaxHistorData
			} else {
				this.historyData = this.ajaxHistorData.slice(0, this.pageSize)
			}
		},
		// 点击某页
		onChange(index) {
			let _start = (index - 1) * this.pageSize
			let _end = index * this.pageSize
			this.historyData = this.ajaxHistorData.slice(_start, _end)
		},
		// 切换每页显示条数
		changPage(val) {
			// 改变每页显示条数，再重新执行分页
			this.pageSize = val
			this.handleListApproveHistory()
		},
		// 查询今天，最近三天，最近七天的数据
		exportQuickHandle(id) {
			let data = {
				query_type: 2,
				serialId: this.serialId
			}
			id === '1' ? (
				data.startTime = moment().format('YYYY-MM-DD 00:00:00'),
				data.endTime = moment().format('YYYY-MM-DD HH:mm:ss')
			) : id === '2' ? (
				data.startTime = moment().add(-3, 'days').format('YYYY-MM-DD HH:mm:ss'),
				data.endTime = moment().format('YYYY-MM-DD HH:mm:ss')
			) : (
				data.startTime = moment().add(-1, 'week').format('YYYY-MM-DD HH:mm:ss'),
				data.endTime = moment().format('YYYY-MM-DD HH:mm:ss')
			)
			this.send_post_data(data)
		},
		// 保存excel
		saveXsls(obj, fileName) {
			let tmpa = document.createElement('a')
			tmpa.download = fileName || '下载'
			tmpa.href = URL.createObjectURL(obj)
			tmpa.click()
			setTimeout(() => {
				URL.revokeObjectURL(obj)
			}, 100)
		},
		// 格式化excel的key
		filterExcelKey(key) {
			switch (key) {
				case 'zformCompany':
					return '发货单位:'
					break
				case 'ztoCompany':
					return '收货单位:'
					break
				case 'zgoods':
					return '收货时间:'
					break
				case 'boxID':
					return '运输箱号:'
					break
				case 'trackID':
					return '运输单号:'
					break
				case 'aid':
					return 'ID序列号:'
					break
				case 'maxTemperature':
					return '最大温度:'
					break
				case 'minTemperature':
					return '最小温度:'
					break
				case 'avgTemperature':
					return '平均温度:'
					break
				case 'interval1':
					return '记录间隔:'
					break
				case 'downTemperature':
					return '温度上限:'
					break
				case 'upTemperature':
					return '温度下限:'
					break
				case 'readPlace':
					return '位置信息:'
					break
				case 'recDelay':
					return '延时时间:'
					break
				case 'tempTime':
					return '启动时间:'
					break
				case 'readTime':
					return '上传时间:'
					break
				case 'qty':
					return '数据总量:'
					break
			}
		},
		// 点击导出excel
		exportExcel() {
			let result = this.result
			console.log(result)
			if (!result || result.length < 1) {
				this.$Message.error(`设备“${this.serialId}”无任何数据记录！`)
				return false
			}
			let header = []
			result[0].aid = this.serialId
			result[0].zformCompany = ''
			result[0].ztoCompany = ''
			result[0].zgoods = ''
			for (let key in result[0]) {
				console.log(key)
				// 跳过无用的属性
				if (key === 'startToReadTemp' || key === 'notes' || key === 'startRecTime' || key === 'batValue' || key === 'phoneNum') {
					continue
				}
				// 添加导出的参数头
				header.push({
					't': this.filterExcelKey(key),
					'v': result[0][key]
				})
			}
			// 添加数据表头
			header.push({
				't': '序号',
				'v': '时间',
				's': '温度'
			})

			// 添加数据
			this.detailsData.forEach(item => {
				header.push({
					't': item.num,
					'v': item.time,
					's': item.data
				})
			})

			let wb = { SheetNames: ['第一页'], Sheets: {}, Props: {} }
			let data = xlsx.utils.json_to_sheet(header)
			data['A1'] = { t: 's', v: '冷链运输温度记录' }
			//  合并单元格
			data['!merges'] = [
				{
					s: {
						c: 3, // 开始列
						r: 0 // 开始取值范围
					},
					e: {
						c: 0, // 结束列
						r: 0 // 结束范围
					}
				}
			]

			wb.Sheets['第一页'] = data
			// 保存
			this.saveXsls(new Blob([this.s2ab(xlsx.write(wb, this.exportType))], {
				type: "application/octet-stream"
			}), `设备${this.serialId}` + '.' + (this.exportType.bookType == "biff2" ? "xls" : this.exportType.bookType))
		},
		// 导出配置
		s2ab(s) {
			if (typeof ArrayBuffer !== 'undefined') {
				let buf = new ArrayBuffer(s.length)
				let view = new Uint8Array(buf)
				for (let i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
				return buf
			} else {
				let buf = new Array(s.length)
				for (let i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF
				return buf
			}
		}
	},
	created() {
		this.get_data()
		this.handleListApproveHistory()
	},
	watch: {
		'detailsData': {
			deep: true,
			handler: function(data) {
				this.handleListApproveHistory()
			}
		}
	}
}
</script>

<style lang="less" scoped>
@import '../assets/css/home';

.filter {
	border-radius: 3px;
	background: rgba(255, 255, 255, .35);
	box-shadow: 0 0 0 1px rgba(255, 255, 255, .3) inset,
		0 .5em 1em rgba(0, 0, 0, .2);
	text-shadow: 0 1px 1px rgba(255, 255, 255, .3);
	position: relative;
	color: #000;

	&:before {
		content: '';
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		z-index: -1;
		filter: blur(5px);
	}

	>h3 {
		text-align: left;
		margin: -15px -15px 0 -15px;
		height: 36px;
		line-height: 36px;
		padding-left: 15px;
		border-bottom: 1px solid rgba(255, 255, 255, .3);
		font-weight: 100;
	}
}

.detail-main {
	.size(60%, 100%);
	overflow-x: auto;
	position: absolute !important;
	right: 0;
	top: 0;
	z-index: 101;
	.filter;

	&:after {
		content: '';
		position: absolute;
		top: 0;
		right: 0;
		bottom: 0;
		left: 0;
		background: rgba(255, 255, 255, .95);
		opacity: .9;
		z-index: -1;
	}

	/deep/ .ivu-collapse-header {
		text-align: left;
		font-weight: 700;
	}

	/deep/ .ivu-collapse-content {
		padding: 0 10px;

		.ivu-collapse-content-box {
			padding: 10px 0;
		}
	}
}

.export-box {
	padding: 15px;
	display: flex;
	align-items: center;

	button,
	>div {
		margin-right: 20px;
	}

	.export {
		margin-left: auto;
	}

	.query-time {
		display: flex;
		align-items: center;

		.sitg {
			margin: 0 10px;
		}
	}
}


.detail-main /deep/ .loading {
	display: flex;
	align-items: center;
	justify-content: center;
	width: 100%;

	.load-bar {
		font-size: 1.5em;
		animation: ani-demo-spin 1s linear infinite;
	}

	.load-bar,
	.load-text {
		color: #333;
	}
}

@keyframes ani-demo-spin {
	from {
		transform: rotate(0deg);
	}

	50% {
		transform: rotate(180deg);
	}

	to {
		transform: rotate(360deg);
	}
}</style>
